package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.core.CartsKey;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.UserService;
import com.dongdongshop.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Component
public class OrderServiceImpl implements OrderService {
    @Resource
    private TbOrderMapper orderMapper;
    @Resource
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Reference(check=false ,timeout=106666)
    private UserService userService;
    //注入工具类
    @Autowired
    private IdWorker idWorker;

    @Override
    public void submitOrder(Long id, List<Cart> cartList, TbUser user) {
        TbAddress address = userService.getAddressInfoById(id);

        for (Cart cart : cartList) {
            TbOrder order = new TbOrder();
            //订单id
            long nextId = idWorker.nextId();
            order.setOrderId(nextId);
            //实付金额
            //order.setPayment(totalPrice);
            //状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭,7、待评价
            order.setStatus("1");
            //订单创建时间
            order.setCreateTime(new Date());
            //用户id
            order.setUserId(user.getUsername());
            //收货人手机
            order.setReceiverMobile(user.getPhone());
            //收货人
            order.setReceiver(address.getContact());
            //商家id
            order.setSellerId(cart.getSellerId());
            orderMapper.insertSelective(order);
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            for (TbOrderItem tbOrderItem : orderItemList) {
                TbOrderItem tbOrderItem1 = new TbOrderItem();
                long nextId2 = idWorker.nextId();
                tbOrderItem1.setId(nextId2);
                tbOrderItem1.setItemId(tbOrderItem.getItemId());
                tbOrderItem1.setOrderId(nextId);
                tbOrderItem1.setTitle(tbOrderItem.getTitle());
                tbOrderItem1.setPrice(tbOrderItem.getPrice());
                tbOrderItem1.setSellerId(cart.getSellerId());
                tbOrderItem1.setNum(tbOrderItem.getNum());
                tbOrderItem1.setPicPath(tbOrderItem.getPicPath());
                orderItemMapper.insertSelective(tbOrderItem1);
            }
        }
        //清除购物车缓存
        redisTemplate.boundHashOps(CartsKey.CARTS_KEY).delete(user.getUsername());

    }
}
